<template>
	<view class="arriving_box">
		<view class="confirm_box">
			<view class="confirm_input_box">
				<view class="input_name">确认位置</view>
				<view class="address_box" @tap="openMap">
					<view v-if="addressTemporary" class="address_detail">{{ addressTemporary }}</view>
					<view v-else class="address_detail_empty">点击获取地址</view>
					<image class="address_icon" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-92.png"></image>
				</view>
			</view>
			<!-- #ifdef APP -->
			<view class="confirm_input_box">
				<view class="input_name">确认本人</view>
				<view class="button_box" @tap="toIdentifyFace">
					<view v-if="!pictureOfSelf" class="button_empty">点击进行人脸验证</view>
					<view v-else class="button_notEmpty">已采集</view>
					<uni-icons type="right" size="16"></uni-icons>
				</view>
			</view>
			<!-- #endif -->
			<view class="confirm_input_box">
				<view class="input_name">备注</view>
				<textarea v-model="description" class="input_box" maxlength="50" auto-height placeholder-class="input_placeholder" placeholder="输入备注，最多50字" />
			</view>
		</view>
		<view class="upload_box">
			<upload v-model="picList" count="3" :sourceType="['album', 'camera']" uploadUrl="/api/mall/order-service-daily/uploadCoverPic"></upload>
			<view class="upload_tips">上传图片，最多3张。</view>
		</view>
		<view class="tips_box">注意：此订单有关联的单独增值服务订单，确认到达后将一起改变订单状态。服务时请注意提供服务</view>
		<view class="footer_box">
			<view class="footer_button" @tap="submitInfo">确认到达，开始服务</view>
		</view>
	</view>
</template>

<script setup>
import { reactive, computed, ref, watch } from 'vue';
import api from '@/api';
import { onLoad, onShow } from '@dcloudio/uni-app';
import config from '@/config';
import { accredit } from '@/hooks/useAppPermission/index';

let orderId = '';
let studioId = '';
let orderInfo = {};
let serviceLonLatInfo = {};
let currentDistance = 0;
let currentLocation = ref('');
let description = ref('');
let picList = reactive([]);
let addressTemporary = ref('');
const pictureOfSelf = ref('');

onLoad(async (data) => {
	orderId = data.orderId;
	studioId = data.studioId;
	uni.setStorageSync('pictureOfSelf', '');
});

onShow(async () => {
	pictureOfSelf.value = uni.getStorageSync('pictureOfSelf');
	console.log('pictureOfSelf.value', pictureOfSelf.value);
	await getOrderInfo();
	serviceLonLatInfo = await getLocationByAddress(orderInfo.address);
	uni.$once('commitCheck', (data) => {
		addressTemporary.value = data.province + data.city + data.district + data.name + data.address;
		currentLocation.value = data.location;
	});
});

watch(currentLocation, (value) => {
	getDistance();
});

const openMap = () => {
	uni.navigateTo({
		url: '/pages/map/index/index'
	});
};
const getOrderInfo = async () => {
	const { data } = await api({
		method: 'get',
		url: `/mall/order/order-detail/dayOrderDetail`,
		data: {
			id: orderId,
			studioId: studioId
		}
	});
	orderInfo = data;
};
const getDistance = async () => {
	if (!currentLocation.value || !serviceLonLatInfo) return;
	const { data } = await api({
		method: 'get',
		url: '/mall/order/order-detail/confirmRealDistance',
		data: {
			startLonLat: currentLocation.value,
			endLonLat: serviceLonLatInfo.location
		}
	});
	currentDistance = data;
};

//根据地址获取经纬度
const getLocationByAddress = (address) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.mapUrl, //腾讯官方逆解析接口，可直接复制
			data: {
				address,
				key: config.mapKey, //自己申请的Key
				output: 'jsonp'
			},
			method: 'GET',
			success(json) {
				if (json.data.status == 1) {
					// json.data.geocodes[0].location
					resolve(json.data.geocodes[0]);
				} else {
					uni.showToast({
						title: '获取该位置经纬度失败,请重试',
						icon: 'none'
					});
					flay.value = true;
					reject();
				}
			},
			fail: (res) => {
				uni.showToast({
					title: '获取该位置经纬度失败,请重试',
					icon: 'none'
				});
				flay.value = true;
				reject();
			}
		});
	});
};
const submitInfo = async () => {
	if (!validateFormInfo()) return false;
	const res = await api({
		method: 'POST',
		url: '/mall/order/order-detail/confirmArrival',
		data: {
			id: orderId,
			confirmLocation: addressTemporary.value,
			confirmPic: picList.join(','),
			confirmRemark: description.value,
			faceUrl: pictureOfSelf.value
		}
	});
	if (res.code != 0) return false;

	pictureOfSelf.value = '';
	uni.showToast({
		title: '确认到达成功'
	});

	uni.redirectTo({
		url: `/pages/petsOrder/arrivingSucceeded/index?orderType=0&id=${orderId}`
	});
};

const validateFormInfo = () => {
	const validationList = [isAddressSelected, isDistanceClose, isPicListEmpty, isFaceSelected];
	return validationList.every((fn) => {
		if (fn instanceof Function) {
			return fn();
		}
	});
};
const isAddressSelected = () => {
	if (!addressTemporary.value) {
		uni.showModal({
			title: '温馨提示',
			content: '请获取当期位置',
			showCancel: false,
			confirmText: '好的'
		});
		return false;
	}
	return true;
};

const isFaceSelected = () => {
	// #ifdef APP
	if (!pictureOfSelf.value) {
		uni.showModal({
			title: '温馨提示',
			content: '请进行人脸验证',
			showCancel: false,
			confirmText: '好的'
		});
		return false;
	}
	//  #endif
	return true;
};

const isDistanceClose = () => {
	if (currentDistance > 3000) {
		uni.showModal({
			title: '温馨提示',
			content: '确认位置距离服务地址过远，请到达后再点击',
			showCancel: false,
			confirmText: '好的'
		});
		return false;
	}
	return true;
};
const isPicListEmpty = () => {
	if (picList.length == 0) {
		uni.showModal({
			title: '温馨提示',
			content: '请上传确认图片，请到达后再点击',
			showCancel: false,
			confirmText: '好的'
		});
		return false;
	}
	return true;
};
const toIdentifyFace = async () => {
	// #ifdef APP
	const status = await accredit('CAMERA');
	if (status != 1) return;
	const status2 = await accredit('RECORD_AUDIO');
	if (status2 != 1) return;
	//  #endif
	uni.navigateTo({
		url: '/pages/petsOrder/identifyFace/index'
	});
};
</script>

<style lang="scss" scoped>
.arriving_box {
	padding: 32rpx;
	padding-bottom: calc(134rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(134rpx + env(safe-area-inset-bottom));

	.confirm_box {
		padding: 48rpx 32rpx;
		background-color: #fff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;

		.confirm_input_box {
			display: flex;
			justify-content: space-between;
			margin-bottom: 64rpx;

			&:last-child {
				margin-bottom: 0px;
			}

			.input_name {
				width: 138rpx;
				margin-right: 24rpx;
				font-weight: bold;
				font-size: 30rpx;
				color: #1b2120;
			}
			.address_box {
				flex: 1;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 26rpx;
				border-bottom: 1rpx solid #e4e6e6;

				.address_detail {
					flex: 1;
					font-size: 30rpx;
					color: #1b2120;
				}
				.address_detail_empty {
					font-size: 30rpx;
					color: #cacccc;
				}
				.address_icon {
					width: 32rpx;
					height: 32rpx;
					margin-left: 18rpx;
				}
			}

			.button_box {
				flex: 1;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 26rpx;
				border-bottom: 1rpx solid #e4e6e6;
				font-size: 30rpx;
				color: #1b2120;

				.button_empty {
					font-size: 30rpx;
					color: #cacccc;
				}

				.button_notEmpty {
					font-size: 30rpx;
					color: #1b2120;
				}
			}

			.input_box {
				flex: 1;
				background-color: #fff;
				padding-bottom: 26rpx;
				border-bottom: 1rpx solid #e4e6e6;
				font-size: 30rpx;
				color: #1b2120;
			}
			::v-deep .input_placeholder {
				font-size: 30rpx;
				color: #cacccc;
			}
		}
	}

	.tips_box {
		margin: 24rpx 0;
		font-size: 24rpx;
		color: #7c807f;
		line-height: 1.4;
	}

	.upload_box {
		padding: 48rpx 32rpx;
		background-color: #fff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		margin-top: 24rpx;

		.upload_tips {
			font-size: 24rpx;
			color: #7c807f;
			margin-top: 24rpx;
		}
	}

	.footer_box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 6rpx 32rpx;
		padding-bottom: calc(6rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(6rpx + env(safe-area-inset-bottom));
		box-sizing: border-box;
		border-top: 1rpx solid #e4e6e6;
		background-color: #ffffff;
		z-index: 1;

		.footer_button {
			height: 88rpx;
			background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
			border-radius: 62rpx;
			font-size: 28rpx;
			color: #ffffff;
			text-align: center;
			line-height: 88rpx;
		}
	}
}
</style>
